package com.zhijian.medical.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.zhijian.medical.dao.local.SangerSjfxMapper;
import com.zhijian.medical.entity.dto.SangerSjfxDto;
import com.zhijian.medical.entity.po.ExperimentProcessSampleLog;
import com.zhijian.medical.entity.po.Sanger;
import com.zhijian.medical.entity.po.SangerSjfx;
import com.zhijian.medical.entity.vo.request.ExperimentProcessSampleSearchVo;
import com.zhijian.medical.entity.vo.request.SangerSjfxSaveOrUpdateVo;
import com.zhijian.medical.entity.vo.request.SangerSjfxSearchVo;
import com.zhijian.medical.entity.vo.response.ExperimentProcessSampleVo;
import com.zhijian.medical.entity.vo.response.SangerSjfxVo;
import com.zhijian.medical.enums.AllExperimentationStepStatusEnum;
import com.zhijian.medical.enums.ExperimentTypeEnum;
import com.zhijian.medical.enums.SangerStatusEnum;
import com.zhijian.medical.enums.StatusEnum;
import com.zhijian.medical.holder.CurrentUserHolder;
import com.zhijian.medical.service.ExperimentProcessSampleLogService;
import com.zhijian.medical.service.ExperimentProcessSampleService;
import com.zhijian.medical.service.SangerService;
import com.zhijian.medical.service.SangerSjfxService;
import com.zhijian.medical.util.AssertUtil;
import com.zhijian.medical.util.JsonUtil;
import com.zhijian.medical.util.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 一代测序-数据分析（测序区、分子诊断室）业务处理层
 *
 * @author HCG
 * @version: 1.0
 * @date 2022-08-16 15:53:39
 */
@Slf4j
@Service
public class SangerSjfxServiceImpl implements SangerSjfxService {

    @Autowired
    private SangerSjfxMapper mapper;

    @Autowired
    private SangerService sangerService;

    @Autowired
    private ExperimentProcessSampleService experimentProcessSampleService;

    @Autowired
    private ExperimentProcessSampleLogService experimentProcessSampleLogService;

    @Override
    public SangerSjfx selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public SangerSjfx selectBySangerId(Long sangerId) {
        return mapper.selectBySangerId(sangerId);
    }

    @Override
    public SangerSjfxVo selectVoById(Long id) {
        return mapper.selectVoById(id);
    }

    @Override
    public SangerSjfxVo selectVoBySangerId(Long sangerId) {
        SangerSjfxVo sangerSjfxVo = mapper.selectVoBySangerId(sangerId);
        if (Objects.isNull(sangerSjfxVo)) {
            return null;
        }
        Sanger sanger = sangerService.selectById(sangerId);
        if (Objects.isNull(sanger)) {
            return null;
        }
        sangerSjfxVo.setResult(sanger.getStatus() > SangerStatusEnum.SJFX.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getCode().byteValue() : AllExperimentationStepStatusEnum.UN_END.getCode().byteValue());
        sangerSjfxVo.setResultStr(sanger.getStatus() > SangerStatusEnum.SJFX.getCode().byteValue() ?
                AllExperimentationStepStatusEnum.END.getDesc() : AllExperimentationStepStatusEnum.UN_END.getDesc());
        String sjfxData = sangerSjfxVo.getSjfxData();
        if (StringUtils.isNotBlank(sjfxData)) {
            sangerSjfxVo.setSjfxDataList(JsonUtil.toArray(sjfxData, SangerSjfxDto.class));
        }
        return sangerSjfxVo;
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public Long insert(SangerSjfx sangerSjfx) {
        Date now = new Date();
        sangerSjfx.setCreateTime(now);
        sangerSjfx.setUpdateTime(now);
        sangerSjfx.setSysarj(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerSjfx.setJfxhdsjdc(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerSjfx.setCycdbrj(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerSjfx.setBgfs(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerSjfx.setHeqpgd(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerSjfx.setPcrcwdytgd(StatusEnum.UN_NORMAL.getCode().byteValue());
        sangerSjfx.setMxgdytgd(StatusEnum.UN_NORMAL.getCode().byteValue());
        return mapper.insert(sangerSjfx) > 0 ? sangerSjfx.getId() : 0L;
    }

    @Override
    public boolean update(SangerSjfx sangerSjfx) {
        Date now = new Date();
        sangerSjfx.setUpdateTime(now);
        return mapper.updateByPrimaryKey(sangerSjfx) != 0;
    }

    @Override
    public Integer count(SangerSjfxSearchVo sangerSjfxSearchVo) {
        return mapper.count(sangerSjfxSearchVo);
    }

    @Override
    public List<SangerSjfxVo> selectList(SangerSjfxSearchVo sangerSjfxSearchVo) {
        return mapper.selectList(sangerSjfxSearchVo);
    }

    @Override
    public Page<SangerSjfxVo> selectPage(SangerSjfxSearchVo sangerSjfxSearchVo) {
        //先直接查总数
        int count = count(sangerSjfxSearchVo);
        //分页
        Page<SangerSjfxVo> page = new Page<>(true, count, sangerSjfxSearchVo.getPageNum(), sangerSjfxSearchVo.getPageSize());
        sangerSjfxSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<SangerSjfxVo> responseVos = this.selectList(sangerSjfxSearchVo);
        page.setData(responseVos);
        return page;
    }

    @Transactional(rollbackFor = Exception.class, value = "localTransactionManager")
    @Override
    public boolean saveOrUpdate(SangerSjfxSaveOrUpdateVo sangerSjfxSaveOrUpdateVo) {
        Long sangerId = sangerSjfxSaveOrUpdateVo.getSangerId();
        Sanger sanger = sangerService.selectById(sangerId);
        AssertUtil.notNull(sanger, "此实验不存在或者已被删除");
        Sanger updateParam = Sanger.builder()
                .id(sangerId)
                .endTime(new Date())
                .build();
        if (sanger.getStatus() < SangerStatusEnum.END.getCode().byteValue()) {
            //将实验的状态修改
            updateParam.setStatus(SangerStatusEnum.END.getCode().byteValue());
        }
        sangerService.updateByPrimaryKeySelective(updateParam);
        List<SangerSjfxDto> sjfxDataList = sangerSjfxSaveOrUpdateVo.getSjfxDataList();
        if (CollectionUtil.isNotEmpty(sjfxDataList)) {
            sangerSjfxSaveOrUpdateVo.setSjfxData(JsonUtil.toString(sjfxDataList));
        }
        SangerSjfx dbParam = new SangerSjfx();
        BeanUtils.copyProperties(sangerSjfxSaveOrUpdateVo, dbParam);
        SangerSjfx oldSangerSjfx = this.selectBySangerId(sangerId);
        if (Objects.isNull(oldSangerSjfx)) {
            this.insert(dbParam);
        } else {
            dbParam.setId(oldSangerSjfx.getId());
            this.update(dbParam);
        }
        List<ExperimentProcessSampleVo> experimentProcessSampleVos = experimentProcessSampleService.selectList(ExperimentProcessSampleSearchVo.builder()
                .mainType(ExperimentTypeEnum.SANGER.getCode().byteValue())
                .experimentProcessId(sangerId)
                .build());
        //保存样本日志
        experimentProcessSampleLogService.saveBatch(experimentProcessSampleVos.stream().map(e -> ExperimentProcessSampleLog.builder()
                .sampleId(e.getId())
                .fishId(sangerId)
                .mainType(ExperimentTypeEnum.SANGER.getCode().byteValue())
                .op(String.format("%s%s-%s", sanger.getName(), sanger.getProcessNumber(), SangerStatusEnum.SJFX.getDesc()))
                .opUser(CurrentUserHolder.getUser().getName())
                .build()).collect(Collectors.toList()));
        return true;
    }

}